<template>
  <ym-icon-button
    v-bind="$attrs"
    @click="click"
    v-if="!open"
  />
  <el-dialog
    v-else
    :title="dialog"
    :before-close="onDialogClose"
    :visible.sync="open"
    destroy-on-close
  >
    <component
      :is="is"
      v-bind="definition"
      @close="close"
    />
  </el-dialog>
</template>
<script>
import YmIconButton from './YmIconButton'
import { VIEW, Views } from '@/store/views'
import { DEFINITION } from "@/store/elementui";

/**
 * 对话框按钮
 *    注意： el-dialog不会主动调用关闭回调
 *
 *    props: {
 *      title: string 对话框标题,
 *      setContent: function 内容生成器 { view: string, definition: object }
 *      ...ym-icon-button
 *    }
 */
export default {
  data () {
    return {
      open: false,
      content: {
        view: 'div',
        [DEFINITION]: {}
      }
    }
  },
  computed: {
    is () {
      return Views[this.content[VIEW]] || this.content[VIEW] || 'div'
    },
    definition () {
      return this.content[DEFINITION]
    }
  },
  props: {
    dialog: {
      type: String,
      default: '消息'
    },
    setContent: {
      type: Function,
      default: () => () => {
        return {
          view: 'div',
          [DEFINITION]: {}
        }
      }
    }
  },
  methods: {
    onDialogClose (done) {
      done()
      this.open = false
    },
    async click () {
      this.content = await this.setContent()
      this.open = true
    },
    close () {
      this.open = false
      this.$emit('click')
    }
  },
  components: {
    YmIconButton
  }
}
</script>
